﻿using System;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WindowsPhoneEssentials.Converters
{
    public class UriToImageBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null) return null;

            var uri = GetUri(value);

            var image = new BitmapImage(uri);
            var imageBrush = new ImageBrush { ImageSource = image };
            return imageBrush;
        }

        private static Uri GetUri(object value)
        {
            if (value is Uri)
            {
                return (Uri) value;
            }
            if (value is string)
            {
                return new Uri((string) value, UriKind.RelativeOrAbsolute);
            }
            throw new NotSupportedException("ImageBrushConverter should only be used on string or Uri values.");
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}